/*
 * Created by:		Mason Staerkel
 * 					Jacob Julich
 * Created on:		March 17, 2011
 * Last updated:	March 23, 2011
 * Function:		Will act as the canvas for our objectdraw program
 */

import java.awt.BorderLayout;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;

public class Canvas1 extends JFrame
{
	private int startX, startY;
	private int endX, endY;
	JLabel instructions = new JLabel("Drag the mouse to draw");
	private int tally;
	Graphics [] holdGraphic;
	
	public Canvas1()
	{
		// Creates the JFrame
		super( "A simple paint program" );
		
		// Initializes variables
		tally = 0;
		holdGraphic = new Graphics[100];
		
		JPanel tarp = new JPanel();
		add( tarp, BorderLayout.CENTER);
		
		//JLabel instructions = new JLabel("Drag the mouse to draw");
		add( instructions, BorderLayout.SOUTH);
		
		MouseHandler handler = new MouseHandler();
		tarp.addMouseListener(handler);
	}	// end constructor
	
	private void paint(Graphics g, int counter)
	{
		int changeX, changeY;
		changeX = endX - startX;
		changeY = endY - startY;
		
		// Below checks if the rectangle was drawn in reverse or not and compensates accordingly
		if ((changeX < 0) && (changeY < 0))
			g.drawRect(endX, endY, -changeX, -changeY);
		else if (changeX < 0)
			g.drawRect(endX, startY, -changeX, changeY);
		else if (changeY < 0)
			g.drawRect(startX, endY, changeX, -changeY);
		else
			g.drawRect(startX, startY, changeX, changeY);
		
		this.holdGraphic[counter] = g;
	}

	private class MouseHandler implements MouseListener
	{
		// MouseListener event handlers
		// event when mouse is pressed
		@Override
		public void mousePressed( MouseEvent e)
		{
			startX = e.getX() + 8;
			startY = e.getY() + 30;
		}
		
		// event when mouse is released
		@Override
		public void mouseReleased( MouseEvent e)
		{
			endX = e.getX() + 8;
			endY = e.getY() + 30;
			
			Graphics g = getGraphics();
			paint(g, tally++);
			
			//g.drawRect(startX, startY, (endX - startX), (endY - startY));
			String newText = String.format("x = %d;  y = %d\n endx = %d;  endy = %d", startX, startY, endX, endY);
			instructions.setText(newText);
		}

		// event when mouse is released immediately after a press
		@Override
		public void mouseClicked(MouseEvent e)
		{
			
		}

		// event when mouse enters area
		@Override
		public void mouseEntered(MouseEvent e)
		{

		}

		// event when mouse exits area
		@Override
		public void mouseExited(MouseEvent e)
		{
			
		}
	}	// end inner class MouseHandler
}	// end class Canvas